<?php
/*
    Copyright (C) 2008 - 2010 Inanta Martsanto
    
    This file is part of Koma.

    Koma is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Koma is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Koma.  If not, see <http://www.gnu.org/licenses/>.
    
    Inanta Martsanto (inanta@inationsoft.com)
*/

class KomaTableModel extends KomaObject
{
    private $_fields = array();
    
    function __construct($table)
    {
        $this->createProperties(array('Table' => $table));
        $this->populateFields($table);
        
    }
    
    function __set($property, $value)
    {
        if(array_key_exists('`'.$property.'`', $this->_fields)) $this->_fields['`'.$property.'`'] = "'".$value."'";
        else parent::__set($property, $value);
    }
    
    function __get($property)
    {
        if(array_key_exists('`'.$property.'`', $this->_fields)) return $this->_fields['`'.$property.'`'];
        return parent::__get($property);
    }
    
    function insert()
    {
        return KomaDatabaseFactory::getInstance()->query("INSERT INTO `".$this->Table."` (".implode(',', array_keys($this->_fields)).") VALUES (".implode(',', $this->_fields).")");
    }
    
    function update($id)
    {
        $update = array();
        foreach($this->_fields as $key => $value) { if($value != null) $update[] = $key."=".$value; }
        
        echo "UPDATE `".$this->Table."` SET ".implode(',', $update)." WHERE `id`='".$id."'";
        
        return KomaDatabaseFactory::getInstance()->query("UPDATE `".$this->Table."` SET ".implode(',', $update)." WHERE id='".$id."'");
    }
    
    private function populateFields()
    {
        $result = KomaDatabaseFactory::getInstance()->query("SELECT * FROM ".$this->Table." LIMIT 1");
        $fields = KomaDatabaseFactory::getInstance()->numFields($result);
        
        for($i = 0; $i < $fields; $i++)
        {
            if(KomaDatabaseFactory::getInstance()->fieldName($i, $result) != 'id') $this->_fields['`'.KomaDatabaseFactory::getInstance()->fieldName($i, $result).'`'] = null;
        }
    }
}
?>